<script setup lang="ts">
import { onMounted, reactive, ref, unref, computed } from 'vue';
import {
  Message,
  PaginationProps,
  TableColumnData
} from '@arco-design/web-vue';
import {
  type OjProblemQueryRequest,
  OjProblemService,
  OjProblemVo,
  type Paging
} from '@/api/gen-api';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import { useRouter } from 'vue-router';
import { OjProblemPageVo } from '@/api/gen-api/models/problem/OjProblemPageVo.ts';
import { getQueryString } from '@/api/gen-api/core/request.ts';
import {
  IconSearch,
  IconRefresh,
  IconPlus,
  IconDownload,
  IconEdit,
  IconDelete,
  IconCode
} from '@arco-design/web-vue/es/icon';

const router = useRouter();
const columns: TableColumnData[] = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 70,
    ellipsis: true
  },
  {
    title: '标题',
    dataIndex: 'title',
    align: 'left',
    width: 120
  },
  {
    title: '内容',
    dataIndex: 'content',
    ellipsis: true,
    align: 'left',
    width: 150
  },
  {
    title: '标签',
    dataIndex: 'tags',
    slotName: 'Tags',
    align: 'center',
    width: 120
  },
  {
    title: '难度',
    dataIndex: 'difficulty',
    align: 'center',
    slotName: 'Difficulty',
    width: 80
  },
  {
    title: '提交数',
    dataIndex: 'submitNum',
    align: 'center',
    width: 70
  },
  {
    title: '通过数',
    dataIndex: 'acceptedNum',
    align: 'center',
    width: 70
  },
  {
    title: '点赞数',
    dataIndex: 'thumbNum',
    align: 'center',
    width: 70
  },
  {
    title: '收藏数',
    dataIndex: 'favourNum',
    align: 'center',
    width: 70
  },
  {
    slotName: 'Controls',
    title: '操作',
    fixed: 'right',
    align: 'center',
    width: 70
  }
];

const queryReq = ref<OjProblemQueryRequest>({
  title: '',
  tags: [],
  difficulty: undefined
});

const paging: Paging = reactive({
  pageNum: 1,
  pageSize: 10
});

// 修改难度选项标签
const contentTypeOptions: SelectOptionData[] = [
  {
    label: '入门',
    value: 0
  },
  {
    label: '进阶',
    value: 1
  },
  {
    label: '挑战',
    value: 2
  }
];

// 难度映射函数
const getDifficultyLabel = value => {
  switch (value) {
    case 0:
    case '简单':
      return '入门';
    case 1:
    case '中等':
      return '进阶';
    case 2:
    case '困难':
      return '挑战';
    default:
      return value;
  }
};

const loading = ref(false);
const data = reactive({
  problemList: [] as OjProblemPageVo[]
});

const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100],
  showJumper: true,
  size: 'medium'
});

const scroll = {
  x: 1200,
  y: 'calc(100vh - 300px)'
};

const handlePageSizeChange = (pageSize: number) => {
  paging.pageSize = pageSize;
  pageData();
};

const handlePageNumberChange = (pageNumber: number) => {
  paging.pageNum = pageNumber;
  pageData();
};

/**
 * 跳转
 */
const handleAddProblem = () => {
  router.push({ name: 'ProblemAdd' });
};

/**
 * 查询数据
 */
const pageData = async () => {
  loading.value = true;
  await OjProblemService.page2(paging, unref(queryReq))
    .then(res => {
      const result = res.result;
      data.problemList = result.records;
      pagination.total = result.totalRow;
      pagination.current = paging.pageNum;
      pagination.pageSize = paging.pageSize;
    })
    .finally(() => {
      loading.value = false;
    });
};

/**
 * 重置查询条件
 */
const reset = () => {
  queryReq.value = {
    title: '',
    tags: [],
    difficulty: undefined
  };
  paging.pageNum = 1;
  pageData();
};

const handleExport = () => {
  const url = '/ojProblem/export';
  // HACK: 待修改
  const proxy = 'http://localhost:8101/api';
  const query = getQueryString({
    ...queryReq.value,
    ...paging
  });
  window.location.href = proxy + url + query;
};

const popoverVisibleList = ref([]);

/**
 * 取消删除操作
 */
const handleCancelDel = (rowIndex: number) => {
  popoverVisibleList.value[rowIndex] = false;
};

const handleDel = (record: OjProblemVo, rowIndex: number) => {
  OjProblemService.remove(record.id).then(() => {
    Message.success('删除成功');
    pageData();
  });
  popoverVisibleList.value[rowIndex] = false;
};

/**
 * 跳转编辑页面
 */
const handleEdit = (record: OjProblemVo) => {
  router.push({ name: 'ProblemEdit', query: { id: record.id } });
};

onMounted(async () => {
  await pageData();
  data.problemList.forEach(() => popoverVisibleList.value.push(false));
});
</script>

<template>
  <div class="container-problem-manage">
    <Breadcrumb :items="['题库', '题目管理']" />
    <a-card class="problem-card">
      <template #title>
        <div class="card-title">
          <icon-code />
          <span>题目管理</span>
          <a-tag v-if="pagination.total">
            共 {{ pagination.total }} 道题目
          </a-tag>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <a-row :gutter="16">
          <a-col :span="20">
            <a-form :model="queryReq" layout="horizontal">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item field="title" label="标题">
                    <a-input
                      v-model="queryReq.title"
                      placeholder="请输入标题"
                      allow-clear
                    >
                      <template #prefix>
                        <icon-search />
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="tags" label="标签">
                    <a-input-tag
                      v-model="queryReq.tags"
                      placeholder="请输入标签并回车"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="difficulty" label="难度">
                    <a-select
                      v-model="queryReq.difficulty"
                      :options="contentTypeOptions"
                      placeholder="请选择题目难度"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-col :span="4" class="search-buttons">
            <a-space>
              <a-button type="primary" @click="pageData">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>

      <!-- 操作区域 -->
      <div class="operation-area">
        <a-row>
          <a-col :span="12">
            <a-button type="primary" @click="handleAddProblem">
              <template #icon>
                <icon-plus />
              </template>
              新增题目
            </a-button>
          </a-col>
          <a-col :span="12" class="export-area">
            <a-button @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出题目
            </a-button>
          </a-col>
        </a-row>
      </div>

      <!-- 表格区域 -->
      <a-table
        row-key="id"
        :bordered="false"
        :scroll="scroll"
        :columns="columns"
        :data="data.problemList"
        :loading="loading"
        :pagination="pagination"
        @page-change="handlePageNumberChange"
        @page-size-change="handlePageSizeChange"
        :stripe="true"
        class="compact-table"
      >
        <template #Tags="{ rowIndex }">
          <div class="tag-container">
            <a-tag
              v-for="tag in data.problemList[rowIndex].tags"
              :key="tag"
              color="arcoblue"
              size="small"
            >
              {{ tag }}
            </a-tag>
          </div>
        </template>
        <template #Difficulty="{ record }">
          <a-tag
            :color="
              record.difficulty === '简单' || record.difficulty === 0
                ? 'green'
                : record.difficulty === '中等' || record.difficulty === 1
                  ? 'orange'
                  : 'red'
            "
            size="small"
          >
            {{ getDifficultyLabel(record.difficulty) }}
          </a-tag>
        </template>
        <template #Controls="{ record, rowIndex }">
          <div class="action-container">
            <a-button
              type="text"
              size="mini"
              @click="handleEdit(record)"
              class="action-button"
            >
              <icon-edit />
            </a-button>
            <a-popover
              v-model:popup-visible="popoverVisibleList[rowIndex]"
              title="确定要删除吗？"
              position="left"
              trigger="click"
              mini
            >
              <template #content>
                <div class="delete-confirm">
                  <p>删除后将无法恢复，确定继续吗？</p>
                  <a-space size="mini">
                    <a-button size="mini" @click="handleCancelDel(rowIndex)">
                      取消
                    </a-button>
                    <a-button
                      size="mini"
                      status="danger"
                      @click="handleDel(record, rowIndex)"
                    >
                      确定
                    </a-button>
                  </a-space>
                </div>
              </template>
              <a-button
                type="text"
                status="danger"
                size="mini"
                class="action-button"
              >
                <icon-delete />
              </a-button>
            </a-popover>
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<style scoped lang="less">
.container-problem-manage {
  padding: 0 20px 20px;

  .problem-card {
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;

      .arco-icon {
        font-size: 16px;
        color: #2759cd;
      }

      span {
        font-size: 15px;
        font-weight: 500;
      }

      .arco-tag {
        margin-left: 8px;
        font-size: 12px;
      }
    }

    .search-area {
      background-color: var(--color-fill-1);
      padding: 12px;
      border-radius: 4px;
      margin-bottom: 12px;

      .search-buttons {
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        height: 32px;
      }

      :deep(.arco-form-item) {
        margin-bottom: 0;

        .arco-form-item-label {
          font-weight: 500;
          font-size: 13px;
        }

        .arco-form-item-content {
          .arco-input,
          .arco-select,
          .arco-input-tag {
            font-size: 13px;
          }
        }
      }
    }

    .operation-area {
      margin-bottom: 12px;

      .export-area {
        display: flex;
        justify-content: flex-end;
      }

      .arco-btn {
        font-size: 13px;
      }
    }

    // 紧凑表格样式
    :deep(.compact-table) {
      font-size: 13px;

      .arco-table-th {
        background-color: var(--color-fill-2);
        font-weight: 500;
        font-size: 13px;
        padding: 8px 10px;
        height: 40px;
      }

      .arco-table-td {
        font-size: 13px;
        padding: 6px 10px;
        height: 36px;
      }

      .arco-table-tr:hover {
        .arco-table-td {
          background-color: var(--color-fill-1);
        }
      }
    }

    // 优化标签样式
    .tag-container {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      justify-content: center;

      .arco-tag {
        margin: 0;
        padding: 0 6px;
        font-size: 12px;
        line-height: 18px;
        height: 20px;
      }
    }

    // 优化操作按钮样式
    .action-container {
      display: flex;
      justify-content: center;
      gap: 8px;

      .action-button {
        padding: 0;
        height: 22px;
        width: 22px;
        min-width: 22px;
        line-height: 22px;

        .arco-icon {
          font-size: 14px;
        }
      }
    }

    .delete-confirm {
      p {
        margin-bottom: 8px;
        font-size: 13px;
      }

      .arco-btn {
        font-size: 12px;
      }
    }
  }

  :deep(.arco-btn) {
    border-radius: 4px;

    &.arco-btn-primary {
      background-color: #2759cd;
      border-color: #2759cd;

      &:hover {
        background-color: #1a3a8f;
        border-color: #1a3a8f;
      }
    }

    &.arco-btn-size-mini {
      height: 22px;
      line-height: 22px;
      font-size: 12px;
    }
  }

  :deep(.arco-tag) {
    border-radius: 2px;

    &.arco-tag-size-small {
      font-size: 12px;
      line-height: 18px;
      height: 20px;
      padding: 0 6px;
    }
  }

  :deep(.arco-pagination) {
    margin-top: 12px;
    font-size: 13px;

    .arco-pagination-item {
      min-width: 28px;
      height: 28px;
      line-height: 28px;
    }

    .arco-select-view {
      font-size: 13px;
    }
  }
}
</style>
